package com.example.coffeeseller_2.views.fragments.yagai_zhuanbei;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.MachineConfig.QRMsger;
import com.example.coffeeseller_2.model.beans.ChooseCoffeeInfo;
import com.example.coffeeseller_2.model.beans.Coffee;
import com.example.coffeeseller_2.model.beans.DealRecorder;
import com.example.coffeeseller_2.model.beans.MachineConfig;
import com.example.coffeeseller_2.model.beans.Step;
import com.example.coffeeseller_2.model.beans.TasteInfo;
import com.example.coffeeseller_2.model.contentprovider.ApplicationConstance;
import com.example.coffeeseller_2.model.contentprovider.ErrorCode;
import com.example.coffeeseller_2.model.databases.DealOrderInfoManager;
import com.example.coffeeseller_2.model.factory.BuyState;
import com.example.coffeeseller_2.model.factory.ChangeLayoutState;
import com.example.coffeeseller_2.model.helper.ChangeLayoutHelper;
import com.example.coffeeseller_2.model.helper.CheckCurMachineState;
import com.example.coffeeseller_2.model.helper.ClearMachine;
import com.example.coffeeseller_2.model.helper.MkCoffeeHelper;
import com.example.coffeeseller_2.model.helper.Trade;
import com.example.coffeeseller_2.model.helper.TradeAnimManager;
import com.example.coffeeseller_2.model.helper.TradeOverDealManager;
import com.example.coffeeseller_2.model.helper.view_helper.TradeLeftInfoViewHelper;
import com.example.coffeeseller_2.model.listenner.MkCoffeeListenner;
import com.example.coffeeseller_2.model.listenner.MsgTransListener;
import com.example.coffeeseller_2.model.listenner.OnQubeimaSureListenner;
import com.example.coffeeseller_2.model.listenner.OnSaomaTimeOutListenner;
import com.example.coffeeseller_2.model.listenner.OnTasteSelectedListenner;
import com.example.coffeeseller_2.model.listenner.OnTradeListenner;
import com.example.coffeeseller_2.model.model.UpdateWaterMaterial;
import com.example.coffeeseller_2.utils.DensityUtil;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.SingleTTs;
import com.example.coffeeseller_2.views.HomeActivity;
import com.example.coffeeseller_2.views.fragments.BasicFragment;
import com.example.coffeeseller_2.widget.BuyProcessView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import cof.ac.inter.CoffMsger;
import cof.ac.inter.ContainerConfig;
import cof.ac.inter.MachineState;

import static com.example.coffeeseller_2.model.factory.PayState.PAYED;
import static com.example.coffeeseller_2.model.factory.PayState.PAYING;
import static com.example.coffeeseller_2.utils.Waiter.doWait;

/**
 * Created by WH on 2018/7/30.
 * 选择口味和支付界面
 * 压盖
 */

public class TasteAndPayFragment extends BasicFragment implements OnTasteSelectedListenner
        , OnTradeListenner, MsgTransListener
        , MkCoffeeListenner, TradeAnimManager.OnAnimEndListener
        , OnSaomaTimeOutListenner, OnQubeimaSureListenner {

    private static String TAG = "TasteAndPayFragment";
    private static long TACK_CUP_LIMIT_TIME = 5 * 60 * 1000;
    private View mContent;
    private LinearLayout mFourthLayout, mTopParent;
    private ImageView mTaijiImage, mCropImage;
    private LinearLayout mMaskLayout;
    private LinearLayout mLeftInfoLayout, mRightInfoLayout;
    private LinearLayout mChangeLayout;
    private TextView mPhoneNum;
    private BuyProcessView buyProcessView;

    private HomeActivity mHomeActivity;
    private Coffee coffee;
    private DealRecorder mDealRecorder;
    private ChooseCoffeeInfo coffeeInfo;
    private List<ContainerConfig> containerConfigs;
    private ChangeLayoutHelper changeLayoutHelper;
    private TradeLeftInfoViewHelper tradeLeftInfoViewHelper;
    private Trade trade;
    private Handler handler;
    private TradeAnimManager tradeAnimManager;
    private MkCoffeeHelper mkCoffeeHelper;
    private Thread checkTakeCupThread = null;
    private Timer checkMachineStateTimer = null;
    private TimerTask checkMachineStateTimeTask = null;

    /*    private int leftMargin;
        private int topMargin;*/
    private Map<Integer, Float> radios;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mContent = inflater.inflate(R.layout.fragment_taste_pay, null, false);
        initView();
        return mContent;
    }

    /*
    * 设置数据
    * */
    public void setData(ChooseCoffeeInfo coffeeInfo) {
        clear();
        this.coffeeInfo = coffeeInfo;
        if (this.coffeeInfo == null || !this.coffeeInfo.isVilid()) {
            return;
        }
        Log.d(TAG, "coffeeInfo!=null");
        if (coffeeInfo.getBuyState() == BuyState.NONE) {
            return;
        }
        mDealRecorder = mDealRecorder.getInstance();
        mDealRecorder.clear();
        DealRecorder.getInstance().setBuyState(coffeeInfo.getBuyState());

        initSharedData();
        initImage();
        changeLayout(ChangeLayoutState.LOADING_DATA, null);
        checkMachineState();
        buyProcessView.setState(BuyProcessView.TASTE_PAY);
        stopTaskClearMachine();
    }

    /*
    * 初始化共享数据
    * */
    private void initSharedData() {

        containerConfigs = new ArrayList<>();
        coffee = this.coffeeInfo.getCoffee();
        radios = new HashMap<>();
        mDealRecorder.setCoffee(coffee);
        coffee.setFormulaID(coffee.getFormulaID());
        mDealRecorder.setFormulaID(coffee.getFormulaID());
        mDealRecorder.setContainerConfigs(containerConfigs);
        mPhoneNum.setText(MachineConfig.getPhone() + "");
        mLeftInfoLayout.setAlpha(0);
        mRightInfoLayout.setAlpha(0);
        tradeLeftInfoViewHelper = new TradeLeftInfoViewHelper(mHomeActivity, coffee, this, mLeftInfoLayout);
        initContainerCofing();
    }

    public void enterAnim() {

        if (DealRecorder.getInstance().getBuyState() == BuyState.ALIPAY_WECHAT_BUY
                || DealRecorder.getInstance().getBuyState() == BuyState.VIPCARD_BUY) {

            tradeAnimManager.showViewAnim(mContent, mCropImage, mFourthLayout, mTaijiImage,
                    mMaskLayout, mLeftInfoLayout, mRightInfoLayout);
        } else if (DealRecorder.getInstance().getBuyState() == BuyState.QUBEIMA_BUY) {

            tradeAnimManager.showViewAnimByQubeima(mContent, mCropImage, mFourthLayout, mTaijiImage,
                    mMaskLayout, mLeftInfoLayout, mRightInfoLayout);
        }

    }

    /*
  * 如果机器状态ok，可以开始制作
  * */
    long firstCheckShiftErrTime = 0;
    long firstCheckWasteErrTime = 0;

    public void checkMachineState() {

        if (checkMachineStateTimer != null || checkMachineStateTimeTask != null) {
            return;
        }

        checkMachineStateTimer = new Timer();
        checkMachineStateTimeTask = new TimerTask() {
            @Override
            public void run() {

                boolean isHottingCheck = CheckCurMachineState.getInstance().isHottingCheck();
                boolean isCleaning = CheckCurMachineState.getInstance().isClearingCheck();
                boolean isHasCupOnShelf = CheckCurMachineState.getInstance().isHasCupOnShelf();
                boolean isShelfRightPlace = CheckCurMachineState.getInstance().isShelfRightPlace();
                boolean isDownTemp = CheckCurMachineState.getInstance().isDownTemp();
                boolean isDownPress = CheckCurMachineState.getInstance().isDownPress();
                boolean isWasteLiquidInRightPlace = CheckCurMachineState.getInstance().isWasteLiquidInRightPlace();
                if (isHottingCheck) {

                    setNotMakingTip("正在准备热水,请稍等！");
                } else if (isCleaning) {

                    setNotMakingTip("机器正在清洗中,请稍等！");
                } else if (isHasCupOnShelf) {

                    setNotMakingTip("有杯子未取走！");
                } else if (isDownTemp || isDownPress) {

                    setNotMakingTip("机器正在准备中,请稍等！");
                    MyLog.d(TAG, "降温或降压中");
                }
      /*          else if (isWasteLiquidInRightPlace) {

                    if (firstCheckWasteErrTime == 0) {
                        firstCheckWasteErrTime = System.currentTimeMillis();
                    }
                    if (firstCheckWasteErrTime > 0 && System.currentTimeMillis() - firstCheckWasteErrTime > 30 * 1000) {
                        setNotMakingTip("抱歉！废液盘出现故障");
                         firstCheckWasteErrTime = 0;
                         stopCheckMachineTimerTask();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mHomeActivity.backToChooseFrag(false);
                                trade.stopTaskCheckPay();
                            }
                        }, 4000);
                    }
                    setNotMakingTip("机器正在准备中,请稍等！");
                }*/
                else {
                    changeLayout(ChangeLayoutState.LOADING_DATA, null);
                    trade.requestQrCode();
                    stopCheckMachineTimerTask();
                }
            }
        };
        checkMachineStateTimer.schedule(checkMachineStateTimeTask, 0, 1000);
    }

    /*
    * 设置不能制作的文字提示
    * */
    private void setNotMakingTip(String errText) {
        if (changeLayoutHelper.getCurViewState() != ChangeLayoutState.MACHINE_TIP) {
            changeLayout(ChangeLayoutState.MACHINE_TIP, null);
        }
        changeLayoutHelper.getCheckTipBeforeMakeViewHelper().setText(errText);
    }

    private void stopCheckMachineTimerTask() {

        if (checkMachineStateTimer != null) {
            checkMachineStateTimer = null;
        }
        if (checkMachineStateTimeTask != null) {
            checkMachineStateTimeTask.cancel();
            checkMachineStateTimeTask = null;
        }
    }

    public void clear() {

        mLeftInfoLayout.setVisibility(View.GONE);
        mRightInfoLayout.setVisibility(View.GONE);
        mFourthLayout.setAlpha(0f);
        mChangeLayout.removeAllViews();
        mMaskLayout.setAlpha(0);
        mTaijiImage.clearAnimation();
        mTaijiImage.setImageBitmap(null);
        mCropImage.clearAnimation();
        mCropImage.setImageBitmap(null);
        mLeftInfoLayout.removeAllViews();
        if (checkTakeCupThread != null) {
            checkTakeCupThread = null;
        }
        trade.stopTaskCheckPay();
        trade.clear();
        changeLayout(ChangeLayoutState.LOADING_DATA, null);
        stopCheckMachineTimerTask();
        handler.removeCallbacksAndMessages(null);
        changeLayoutHelper.getMakingViewHelper().clear();
        ApplicationConstance.getInstance().setPayed(false);
        mContent.setAlpha(0f);
    }

    private void initView() {
        mFourthLayout = (LinearLayout) mContent.findViewById(R.id.fourthLayout);
        mTopParent = (LinearLayout) mContent.findViewById(R.id.topParent);
        mTaijiImage = (ImageView) mContent.findViewById(R.id.taijiImage);
        mCropImage = (ImageView) mContent.findViewById(R.id.cropImage);
        mMaskLayout = (LinearLayout) mContent.findViewById(R.id.maskLayout);
        mChangeLayout = (LinearLayout) mContent.findViewById(R.id.changeLayout);
        mPhoneNum = (TextView) mContent.findViewById(R.id.phoneNum);
        mLeftInfoLayout = (LinearLayout) mContent.findViewById(R.id.leftInfoLayout);
        mRightInfoLayout = (LinearLayout) mContent.findViewById(R.id.rightInfoLayout);
        buyProcessView = (BuyProcessView) mContent.findViewById(R.id.buyProgressView);
        mHomeActivity = (HomeActivity) getActivity();
        handler = new Handler();
        mkCoffeeHelper = new MkCoffeeHelper();
        changeLayoutHelper = new ChangeLayoutHelper(mHomeActivity);
        mkCoffeeHelper.setMkResultListenner(this);
        changeLayoutHelper.getMakingViewHelper().setMkCoffeeHelper(mkCoffeeHelper);
        trade = Trade.getInstance();
        trade.init(mHomeActivity, this, this);
        tradeAnimManager = new TradeAnimManager(mHomeActivity, this);
        mContent.setAlpha(0f);
    }

    private void initContainerCofing() {

        if (coffee.getStepList() != null && coffee.getStepList().size() > 0) {
            List<Step> steps = coffee.getStepList();
            for (int i = 0; i < steps.size(); i++) {
                Step step = steps.get(i);
                ContainerConfig originalConfig = step.getContainerConfig();
                ContainerConfig containerConfig = new ContainerConfig();
                containerConfig.setMaterial_time(originalConfig.getMaterial_time());
                containerConfig.setWater_interval(originalConfig.getWater_interval());
                containerConfig.setWater_type(originalConfig.getWater_type());
                containerConfig.setContainer(originalConfig.getContainer());
                containerConfig.setRotate_speed(originalConfig.getRotate_speed());
                containerConfig.setStir_speed(originalConfig.getStir_speed());
                containerConfig.setWater_capacity(originalConfig.getWater_capacity());
                containerConfigs.add(i, containerConfig);
                TasteInfo tasteInfo = new TasteInfo();
                tasteInfo.setTastes(step.getTastes());
                tasteInfo.setStepId(i);
                tasteInfo.setName(step.getMaterial().getName());
                if (DealRecorder.getInstance().getBuyState() == BuyState.ALIPAY_WECHAT_BUY
                        || DealRecorder.getInstance().getBuyState() == BuyState.VIPCARD_BUY) {
                    //如果是支付宝、会员卡、微信方式，在左侧添加口味选择条

                    tradeLeftInfoViewHelper.addToTasteContainer(tasteInfo);
                } else if (DealRecorder.getInstance().getBuyState() == BuyState.QUBEIMA_BUY) {
                    //如果是取杯码，在右侧添加口味选择条
                    changeLayoutHelper.getQuebiemaTasteViewHelper().setDate(coffee, this, this);
                    changeLayoutHelper.getQuebiemaTasteViewHelper().addToTasteContainer(tasteInfo);
                }


            }

        }
    }

    private void initImage() {

        BuyState buyState = DealRecorder.getInstance().getBuyState();
        if (buyState == BuyState.NONE) {
            return;
        } else if (buyState == BuyState.QUBEIMA_BUY) {//取杯码

            mCropImage.setImageBitmap(coffee.getImageBitmap());
            int endRightMargin = (int) (DensityUtil.getScreenHeight(mHomeActivity) * 0.45);
            mCropImage.setPadding(0, 0, endRightMargin, 0);
            mCropImage.requestLayout();
            mCropImage.invalidate();

        } else { //支付宝、微信、会员卡

            int leftMargin = this.coffeeInfo.getLocationX() - this.coffeeInfo.getMinWidth() / 2;
            int topMargin = this.coffeeInfo.getLocationY() - this.coffeeInfo.getMinHeight() / 2;
            tradeAnimManager.initData(leftMargin, topMargin, coffee.isHaveTaste(),
                    coffeeInfo.getMinWidth(), coffeeInfo.getMinHeight());
            mCropImage.setImageBitmap(coffeeInfo.getCropImage());
            int left = leftMargin;
            int top = topMargin;
            int right = DensityUtil.getScreenWidth(mHomeActivity) - leftMargin - coffeeInfo.getMinWidth();
            int bottom = DensityUtil.getScreenHeight(mHomeActivity) - topMargin - coffeeInfo.getMinHeight();
            mCropImage.setPadding(left, top, right, bottom);
            mCropImage.requestLayout();
            mCropImage.invalidate();
        }
    }


    private void changeLayout(final ChangeLayoutState changeLayoutState, final Bitmap bitmap) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                mChangeLayout.removeAllViews();
                if (changeLayoutState == ChangeLayoutState.PAY_SUCCESS) {
                    tradeLeftInfoViewHelper.setBackInVisiable();
                }
                mChangeLayout.addView(changeLayoutHelper.getViewByState(changeLayoutState, bitmap));
            }
        });

    }

    /*
    * 检查是否取杯
    * */
    private void checkTakeCup() {

        if (checkTakeCupThread != null) {
            return;
        }
        if (checkTakeCupThread == null) {
            final CoffMsger coffMsger = CoffMsger.getInstance();


            checkTakeCupThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    MachineState machineState = coffMsger.getLastMachineState();
                    boolean isHaveCup = machineState.hasCupOnShelf();
                    long takeCupTime = System.currentTimeMillis();
                    final boolean isCupInDoor = machineState.isLittleDoorOpen();
                    final long startCheckTime = System.currentTimeMillis();

                    while (true) {
                        //如果五分钟内没有取杯
                        if (System.currentTimeMillis() - startCheckTime > TACK_CUP_LIMIT_TIME) {

                            checkTakeCupThread = null;
                            handler.post(new Runnable() {
                                @Override
                                public void run() {
                                    Log.d(TAG, "> TACK_CUP_LIMIT_TIME");
                                    mHomeActivity.backToChooseFrag(true);
                                    trade.stopTaskCheckPay();
                                    ApplicationConstance.getInstance().setCurErrCode(ErrorCode.TAKE_CUP_OVER_TIME);

                                }
                            });

                            break;
                        }

                        machineState = coffMsger.getLastMachineState();
                        /*
                        * 针对压盖
                        * */
                        if (!machineState.isLittleDoorOpen()) {//要是取杯门打开了，才判断杯子有没有被取走
                            continue;
                        }
                        isHaveCup = machineState.hasCupOnShelf();
                        takeCupTime = System.currentTimeMillis();
                        Log.d(TAG, "isHaveCup= " + isHaveCup);
                        if (!isHaveCup) {

                            changeLayout(ChangeLayoutState.TAKECUP_SUCCESS, null);

                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    checkTakeCupThread = null;
                                    Log.d(TAG, "ChangeLayoutState.TAKECUP_SUCCESS");
                                    mHomeActivity.backToChooseFrag(true);
                                    trade.stopTaskCheckPay();

                                }
                            }, 4000);
                            break;
                        }

                        doWait(1000);
                    }

                }
            });
        }
        checkTakeCupThread.start();
    }

    /*
 * 清洗机器
 * */
    private Timer clearMachineTimer;
    private TimerTask clearMachineTimerTask;

    public void stopTaskClearMachine() {

        if (clearMachineTimer != null) {

            clearMachineTimer.cancel();
        }
        clearMachineTimer = null;
        clearMachineTimerTask = null;
    }

    public void clearMachine(final List<ContainerConfig> containerConfigs) {

        if (clearMachineTimer != null || clearMachineTimerTask != null) {
            return;
        }

        MyLog.W(TAG, "clearMachine");
        final long startTime = System.currentTimeMillis();
        if (clearMachineTimer == null) {
            clearMachineTimer = new Timer();
        }
        if (clearMachineTimerTask == null) {
            clearMachineTimerTask = new TimerTask() {
                @Override
                public void run() {
                    //关门发送清洗指令
                    //   boolean canSendCom=CheckCurMachineState.getInstance().isDoorCloseMachineTest() && ClearMachine.isClearOver;

                    //针对手动门，不压盖的机器
                    boolean canSendCom = CheckCurMachineState.getInstance()
                            .getMachineState().isCupShelfRightPlace() && ClearMachine.isClearOver;

    /*                //针对自动门，压盖

                    *//*isWasteLiquidInRightPlace() false 表示 可以清洗 *//*
                    boolean canSendCom = !CheckCurMachineState.getInstance()
                            .getMachineState().isWasteLiquidInRightPlace()
                            && ClearMachine.isClearOver;*/

                    if (canSendCom) {
                        MyLog.W(TAG, "clearMachine can send");
                        boolean isResultSuccess = ClearMachine.clearMachineByHotWater(mHomeActivity, 100, 0);//200：20ml

                        if (isResultSuccess) {
                            UpdateWaterMaterial.update(mHomeActivity, 100 * 10);
                            MyLog.W(TAG, "clearMachine success!");

                        } else {

                            MyLog.W(TAG, "clearMachine failed!");
                        }
                        MyLog.W(TAG, "clearMachine  lastClearMachineTime="
                                + ApplicationConstance.getInstance().getLastClearMachineTime());
                        stopTaskClearMachine();
                    } else if (System.currentTimeMillis() - startTime > 30 * 1000) {
                        MyLog.W(TAG, "clearMachine time > 30 * 1000!");
                        stopTaskClearMachine();
                    }
                }
            };
        }
        clearMachineTimer.schedule(clearMachineTimerTask, 0, 2000);
    }

    @Override
    public void getTasteRadio(float radio, int stepId) {
        if (containerConfigs == null || containerConfigs.size() <= 0 || stepId >= containerConfigs.size()) {
            return;
        }
        Log.d(TAG, "old materialTime= " + containerConfigs.get(stepId).getMaterial_time());
        int materialTime = Math.round(radio * containerConfigs.get(stepId).getMaterial_time());
        containerConfigs.get(stepId).setMaterial_time(materialTime);

        Log.d(TAG, "new materialTime= " + containerConfigs.get(stepId).getMaterial_time());

        Log.d(TAG, "radio = " + radio);
        radios.put(stepId, radio);
    }

    @Override
    public void getQrBitmap(final Bitmap bitmap) {

        Log.d(TAG, "getQrBitmap = " + bitmap);

        //设置二维码后需要开启循环检测
        if (bitmap == null) {
            changeLayout(ChangeLayoutState.LOADING_DATA, bitmap);
            trade.requestQrCode();
        } else {

            changeLayout(ChangeLayoutState.SAOMA, bitmap);
            trade.beginTaskCheckPay();
            tradeLeftInfoViewHelper.setTimeOutListenner(this);

        }
    }

    @Override
    public void isPaying() {
        Log.d(TAG, "isPaying occured");

        if (DealRecorder.getInstance().getPayState() != PAYING) {
            DealRecorder.getInstance().setPayState(PAYING);
            if (changeLayoutHelper.getCurViewState() == ChangeLayoutState.SAOMA) {
                changeLayoutHelper.getViewByState(ChangeLayoutState.SAOMA_SUCCESS, null);
                tradeLeftInfoViewHelper.resetTimeCount();
            }

        }
    }

    @Override
    public void payingErr() {
        //处在支付中30s未完成支付
        Log.d(TAG, "payingErr occured");
        if (changeLayoutHelper.getCurViewState() == ChangeLayoutState.SAOMA_SUCCESS) {
            changeLayoutHelper.getViewByState(ChangeLayoutState.SAOMA_HAS_ERR, null);
        }
        //  trade.stopTaskCheckPay();

    }

    @Override
    public void hasPayed() {
        Log.d(TAG, "hasPayed occured");

        if (DealRecorder.getInstance().getPayState() != PAYED) {
            trade.stopTaskCheckPay();
            trade.clear();
            DealRecorder.getInstance().setPayState(PAYED);
            ApplicationConstance.getInstance().setPayed(true);
            DealOrderInfoManager.getInstance(mHomeActivity).addToTable(DealRecorder.getInstance());
            if (changeLayoutHelper.getCurViewState() == ChangeLayoutState.SAOMA
                    || changeLayoutHelper.getCurViewState() == ChangeLayoutState.SAOMA_SUCCESS
                    || changeLayoutHelper.getCurViewState() == ChangeLayoutState.SAOMA_HAS_ERR) {
                changeLayout(ChangeLayoutState.PAY_SUCCESS, null);
                tradeLeftInfoViewHelper.countDownTimeClose();
                tradeLeftInfoViewHelper.setSeekbarEnable();
            }
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    changeLayout(ChangeLayoutState.WAIT_MAKING, null);
                    buyProcessView.setState(BuyProcessView.MAKING);
                    DealRecorder.getInstance().setContainerConfigs(containerConfigs);
                    DealRecorder.getInstance().setRadios(radios);
                    mkCoffeeHelper.startMkCoffee(containerConfigs);

                }
            }, 4000);
        }
    }

    @Override
    public void qubeimaSureClick() {
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (tradeLeftInfoViewHelper != null) {
                    tradeLeftInfoViewHelper.countDownTimeClose();
                }
                DealRecorder.getInstance().setPayState(PAYED);
                ApplicationConstance.getInstance().setPayed(true);
                DealOrderInfoManager.getInstance(mHomeActivity).addToTable(DealRecorder.getInstance());

                changeLayout(ChangeLayoutState.WAIT_MAKING, null);
                buyProcessView.setState(BuyProcessView.MAKING);
                DealRecorder.getInstance().setContainerConfigs(containerConfigs);

                mkCoffeeHelper.startMkCoffee(containerConfigs);

            }
        });
    }

    @Override
    public void onMsgArrived(Object msg) {
        MyLog.d(TAG, "one msg arrived");
        trade.dealMsgArrived(msg);
    }

    @Override
    public void getMkResult(final DealRecorder dealRecorder, final boolean success, final boolean isCalculateMaterial) {


        if (dealRecorder == null) {

            MyLog.W(TAG, "getMkResult dealRecorder == null");
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mHomeActivity.backToChooseFrag(true);
                }
            }, 4000);
            return;
        }
        final DealRecorder recorder = dealRecorder;
        new Thread(new Runnable() {
            @Override
            public void run() {

                String bunkers = "";
                if (isCalculateMaterial) {

                    MyLog.d(TAG, "isCalculateMaterial= " + isCalculateMaterial);

                    //更新数据库原料表
                    bunkers = TradeOverDealManager.updateMaterial(recorder, mHomeActivity);
                }

                //上报交易结果给服务器

                QRMsger qrMsger = new QRMsger();
                DealRecorder newDealRecorder = qrMsger.reportTradeToServer(recorder, bunkers);

                //更新本地交易记录
                DealOrderInfoManager.getInstance(mHomeActivity).update(newDealRecorder);

                mHomeActivity.updateCoffee();

                //制作后清洗
                clearMachine(null);
               /* if (ClearMachine.isClearOver) {
                    clearMachine(null);
                }*/
            }
        }).start();

        if (success) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    buyProcessView.setState(BuyProcessView.TAKE_CUP);

                    changeLayout(ChangeLayoutState.MAKING_FINISH, null);
                    checkTakeCup();

                    SingleTTs.getSingleTTs().Speak(mHomeActivity.getResources().getString(R.string.making_finish_tip));
                }
            });

        } else {

            handler.post(new Runnable() {
                @Override
                public void run() {

                    if (DealRecorder.getInstance().getBuyState() == BuyState.QUBEIMA_BUY) {
                        SingleTTs.getSingleTTs().Speak(mHomeActivity.getResources().getString(R.string.making_failed_qubeima_tip));
                    } else {
                        SingleTTs.getSingleTTs().Speak(mHomeActivity.getResources().getString(R.string.making_failed_tip));
                    }
                    //   SingleTTs.getSingleTTs().Speak(mHomeActivity.getResources().getString(R.string.making_failed_tip));
                    changeLayout(ChangeLayoutState.MAKING_FAILED, null);
                    Log.d(TAG, "ChangeLayoutState.MAKING_FAILED");

                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mHomeActivity.backToChooseFrag(true);
                        }
                    }, 4000);

                }
            });
        }

    }

    @Override
    public void animEnd() {
        if (tradeLeftInfoViewHelper != null) {
            tradeLeftInfoViewHelper.countDownTime();
        }
        mFourthLayout.clearAnimation();
        mLeftInfoLayout.clearAnimation();
        mRightInfoLayout.clearAnimation();
        mMaskLayout.clearAnimation();
        mTaijiImage.clearAnimation();
        mCropImage.clearAnimation();
    }

    @Override
    public void timeOut() {
        if (changeLayoutHelper.getCurViewState() == ChangeLayoutState.SAOMA) {
            changeLayoutHelper.getSaomaViewHelper().setSaomaTimeOut();
        }
    }


}
